import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'
import router from '@/router'

const request = axios.create({
  baseURL: import.meta.env.VITE_URL
})

request.interceptors.request.use(
  config => {
    // 如果请求的是个人中心和购物车，则在请求头中添加token
    const store = useUserStore()
    if (store.userInfo.token) {
      config.headers.Authorization = `Bearer ${store.userInfo.token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

request.interceptors.response.use(
  res => {
    return res
  },
  err => {
    if (
      router.currentRoute.value.fullPath.includes('user') ||
      router.currentRoute.value.fullPath.includes('cart')
    ) {
      if (err.response.status === 401) {
        router.push('/login')
        ElMessage.error('请先登录')
      } else {
        ElMessage.error(err.response?.data.message)
      }
    }
    return Promise.reject(err)
  }
)

export default request
